import React from 'react';
import createG2 from 'g2-react';
import { Stat } from 'g2';

function formatter(text, item) {
  const point = item.point; // 每个弧度对应的点
  let proportion = point['..percent']; // ..proportion 字段由Stat.summary.proportion统计函数生成
  proportion = `${(proportion * 100).toFixed(2)}%`;
  return `<span class="test-item">${text}${proportion}</span>`;
}

class ChartOfCheckNum extends React.PureComponent {
  constructor(props) {
    super(props);

    this.state = {
      data: [],
    };
    this.initPie();
  }
  componentWillReceiveProps(nextProps) {
    this.setState({
      data: nextProps.data
    }, () => {
      this.initPie();
    });
  }
  initPie() {
    this.Pie = createG2((chart) => {
      chart.coord('theta', {
        radius: 0.6,
      });
      chart.legend({
        itemWrap: true,
        title: null,
        unChecked: '#fff',
        word: {
          fill: '#fff',
        },
        back: {
          fill: 'red'
        },
        dx: 0,
        dy: 0,
        mode: false,
        formatter: (val) => {
          let value;
          for (let i = 0, len = this.state.data.length; i < len; i++) {
            const obj = this.state.data[i];
            if (obj.name === val) {
              value = `${val}:${(obj.value * 100).toFixed(2)}%`;
            }
          }
          return value;
        },
      });
      chart.intervalStack()
        .position(Stat.summary.percent('value'))
        .color('name', ['#00AAFF', '#FF6565'])
        .label('name*..percent', {
          custom: true, // 使用自定义文本
          renderer: formatter, // 格式化文本的函数
          labelLine: true, // 不显示文本的连接线
        });
      chart.tooltip(false);
      chart.legend({
        position: 'bottom',
      });
      chart.render();
    });
  }
  render() {
    const { data } = this.state;
    const Pie = this.Pie;

    return (
      <div className="chart-wrap" style={{ paddingTop: 12 }}>
        <Pie
          data={data}
          width={500}
          height={320}
          forceFit
        />
        <span className="line" />
      </div>
    );
  }
}

export default ChartOfCheckNum;
